from flask import request, jsonify
from flask_jwt_extended import jwt_required, get_jwt_identity
from werkzeug.security import check_password_hash, generate_password_hash

from .extensions import db
from .models import User


def init_profile_routes(app):
    @app.route('/api/auth/profile', methods=['GET'])
    @jwt_required()
    def get_profile():
        # 获取当前用户ID
        current_user_id = get_jwt_identity()

        # 查询用户信息
        user = User.query.get(current_user_id)
        if not user:
            return jsonify({
                'success': False,
                'message': '用户不存在'
            }), 404

        # 返回用户信息
        return jsonify({
            'success': True,
            'username': user.username
        })

    @app.route('/api/auth/update_profile', methods=['POST'])
    @jwt_required()
    def update_profile():
        current_user_id = get_jwt_identity()
        user = User.query.get(current_user_id)

        if not user:
            return jsonify({
                'success': False,
                'message': '用户不存在'
            }), 404

        data = request.get_json()
        current_password = data.get('current_password')
        new_password = data.get('new_password')
        new_username = data.get('new_username')

        # 验证当前密码
        if not check_password_hash(user.password, current_password):
            return jsonify({
                'success': False,
                'message': '当前密码错误'
            }), 400

        try:
            # 更新用户名
            if new_username and new_username != user.username:
                # 检查新用户名是否已存在
                if User.query.filter_by(username=new_username).first():
                    return jsonify({
                        'success': False,
                        'message': '用户名已存在'
                    }), 400
                user.username = new_username

            # 更新密码
            if new_password:
                user.password = generate_password_hash(new_password)

            db.session.commit()

            # 如果更新成功，生成新的token
            from flask_jwt_extended import create_access_token
            token = create_access_token(identity=user.user_id)

            return jsonify({
                'success': True,
                'message': '个人资料更新成功',
                'username': user.username,
                'token': token
            })

        except Exception as e:
            db.session.rollback()
            return jsonify({
                'success': False,
                'message': f'更新失败: {str(e)}'
            }), 500